import JSEncrypt from 'jsencrypt'
import CryptoJS from 'crypto-js'

const pk = window.$app.pk

const generateRandomString = () => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  const charactersLength = characters.length;

  for (let i = 0; i < 32; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
};

export function genAesKey() {
  return CryptoJS.enc.Utf8.parse(generateRandomString());
}

export function str2Base64(str) {
  return CryptoJS.enc.Base64.stringify(str);
};

export function encryptAes(key) {
  const encryptor = new JSEncrypt();
  encryptor.setPublicKey(pk);
  return encryptor.encrypt(key)
}

export function encryptData(data, aesKey) {
  if (typeof data === 'object') {
    data = JSON.stringify(data)
  } else {
    data = data.toString()
  }

  const result = CryptoJS.AES.encrypt(data, aesKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })

  return result.toString()
}